package com.bupt.hotel.hvac.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bupt.hotel.hvac.mapper.CheckInRecordMapper;
import com.bupt.hotel.hvac.model.dto.CheckInDTO;
import com.bupt.hotel.hvac.model.entity.CheckInRecord;
import com.bupt.hotel.hvac.service.CentralControllerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 入住服务控制器 - 统一接口标准
 * 提供入住相关功能
 */
@Slf4j
@RestController
@RequestMapping("/api/checkin")
public class CheckInController {

    private final CentralControllerService centralControllerService;
    private final CheckInRecordMapper checkInRecordMapper;

    public CheckInController(CentralControllerService centralControllerService,
                            CheckInRecordMapper checkInRecordMapper) {
        this.centralControllerService = centralControllerService;
        this.checkInRecordMapper = checkInRecordMapper;
    }

    /**
     * 获取所有空闲房间号
     * GET /api/checkin/available-rooms
     */
    @GetMapping("/available-rooms")
    public List<String> getAvailableRooms() {
        // 查询所有未退房的房间
        List<CheckInRecord> occupiedRecords = checkInRecordMapper.selectList(
                new LambdaQueryWrapper<CheckInRecord>()
                        .eq(CheckInRecord::getCheckedOut, false));
        
        List<String> occupiedRoomIds = occupiedRecords.stream()
                .map(CheckInRecord::getRoomId)
                .collect(Collectors.toList());
        
        // 假设房间号为101-105（根据实际情况调整）
        List<String> allRoomIds = List.of("101", "102", "103", "104", "105");
        
        return allRoomIds.stream()
                .filter(roomId -> !occupiedRoomIds.contains(roomId))
                .collect(Collectors.toList());
    }

    /**
     * 顾客入住指定房间
     * GET /api/checkin/{roomId}
     */
    @GetMapping("/{roomId}")
    public Map<String, Object> checkIn(@PathVariable String roomId) {
        log.info("办理入住 - 房间: {}", roomId);
        
        try {
            // 创建默认的入住DTO（使用GET请求时采用默认值）
            CheckInDTO dto = new CheckInDTO();
            dto.setRoomId(roomId);
            dto.setGuestName("Guest"); // 默认客户名
            dto.setGuestPhone(""); // 默认空
            dto.setIdCard(""); // 默认空
            dto.setStayDays(1); // 默认入住1天
            dto.setRoomType(com.bupt.hotel.hvac.model.enums.RoomType.STANDARD); // 默认标准间
            dto.setMode(com.bupt.hotel.hvac.model.enums.ACMode.COOLING); // 默认制冷模式
            
            Map<String, Object> result = centralControllerService.checkIn(dto);
            return result;
        } catch (Exception e) {
            log.error("办理入住失败: {}", e.getMessage());
            Map<String, Object> result = new HashMap<>();
            result.put("error", e.getMessage());
            return result;
        }
    }

    /**
     * 顾客入住指定房间（POST方式，支持完整参数）
     * POST /api/checkin/{roomId}
     */
    @PostMapping("/{roomId}")
    public Map<String, Object> checkInByPost(@PathVariable String roomId,
                                              @RequestBody(required = false) Map<String, Object> requestBody) {
        log.info("办理入住 (POST) - 房间: {}", roomId);
        
        try {
            CheckInDTO dto = new CheckInDTO();
            dto.setRoomId(roomId);
            
            // 从请求体中提取参数，如果没有则使用默认值
            if (requestBody != null) {
                dto.setGuestName((String) requestBody.getOrDefault("guestName", "Guest"));
                dto.setGuestPhone((String) requestBody.getOrDefault("guestPhone", ""));
                dto.setIdCard((String) requestBody.getOrDefault("idCard", ""));
                dto.setStayDays((Integer) requestBody.getOrDefault("stayDays", 1));
                
                String roomTypeStr = (String) requestBody.getOrDefault("roomType", "STANDARD");
                dto.setRoomType(com.bupt.hotel.hvac.model.enums.RoomType.valueOf(roomTypeStr));
                
                String modeStr = (String) requestBody.getOrDefault("mode", "COOLING");
                dto.setMode(com.bupt.hotel.hvac.model.enums.ACMode.valueOf(modeStr));
            } else {
                // 使用默认值
                dto.setGuestName("Guest");
                dto.setGuestPhone("");
                dto.setIdCard("");
                dto.setStayDays(1);
                dto.setRoomType(com.bupt.hotel.hvac.model.enums.RoomType.STANDARD);
                dto.setMode(com.bupt.hotel.hvac.model.enums.ACMode.COOLING);
            }
            
            Map<String, Object> result = centralControllerService.checkIn(dto);
            return result;
        } catch (Exception e) {
            log.error("办理入住失败: {}", e.getMessage());
            Map<String, Object> result = new HashMap<>();
            result.put("error", e.getMessage());
            return result;
        }
    }
}
